package com.zynn.common.core.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 描述: 自定义拦截器 logback requestUUID
 *
 * @author 刘天元
 * @create 2018年10月8日14:06:52
 **/

public class ControllerInterceptor extends HandlerInterceptorAdapter {

    private Logger LOGGER = LoggerFactory.getLogger(ControllerInterceptor.class);


    /**
     * 在请求处理之前回调方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String requestId = MDC.get("requestId");
        if (requestId == null || "".equals(requestId)) {
            requestId = request.getHeader("requestid");
            MDC.put("requestId", requestId);
            LOGGER.debug("ControllerInterceptor preHandle 在请求处理之前生成 logback requestId:{}", requestId);
        }
        // 只有返回true才会继续向下执行，返回false取消当前请求
        return true;
    }


    /**
     * 请求处理之后回调方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        /* 线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
        MDC.remove("requestUUID");
        LOGGER.debug("ControllerInterceptor postHandle 请求处理之后清除 logback MDC requestUUID");
    }

    /**
     * 整个请求处理完毕回调方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        /*整个请求线程结束后需要清除,否则当前线程会一直占用这个requestId值 */
        MDC.clear();
        LOGGER.debug("ControllerInterceptor afterCompletion 整个请求处理完毕清除 logback MDC requestUUID");
    }
}